

package com.zdkj.subway.stm.controller;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.core.util.ObjectUtil;
import com.alibaba.excel.EasyExcel;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.toolkit.Wrappers;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zdkj.admin.api.entity.SysDictItem;
import com.zdkj.common.core.constant.CommonConstants;
import com.zdkj.common.core.util.R;
import com.zdkj.common.log.annotation.SysLog;
import com.zdkj.common.security.util.ObjectUtils;
import com.zdkj.subway.stm.constant.StmConstans;
import com.zdkj.subway.stm.constant.StmTableCommon;
import com.zdkj.subway.stm.dto.out.SwStHandworkCleanRecordDTO;
import com.zdkj.subway.stm.dvo.SwStmStationDataEntryLogDvo;
import com.zdkj.subway.stm.entity.SwStHandworkCleanRecord;
import com.zdkj.subway.stm.entity.SwStTvmSupplementCurrency;
import com.zdkj.subway.stm.entity.SwStmStationDataEntryLog;
import com.zdkj.subway.stm.fegin.SystemUserService;
import com.zdkj.subway.stm.mapper.SwStHandworkCleanRecordMapper;
import com.zdkj.subway.stm.service.SwStHandworkCleanRecordService;
import com.zdkj.subway.stm.service.SwStmStationDataEntryLogService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.URLDecoder;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;


/**
 * 手工清出数据 主表
 *
 * @author songtuo
 * @date 2020-07-07 18:08:07
 */
@RestController
@AllArgsConstructor
@RequestMapping("/swsthandworkcleanrecord")
@Api(value = "swsthandworkcleanrecord", tags = "手工清出数据 主表管理")
@Slf4j
public class SwStHandworkCleanRecordController {

    private final SwStHandworkCleanRecordService swStHandworkCleanRecordService;


    private final SystemUserService systemUserService;

    private final SwStmStationDataEntryLogService swStmStationDataEntryLogService;
    @Resource
    private SwStHandworkCleanRecordMapper swStHandworkCleanRecordMapper;

    /**
     * 分页查询
     *
     * @param page                    分页对象
     * @param swStHandworkCleanRecord 手工清出数据 主表
     * @return
     */
    @ApiOperation(value = "分页查询", notes = "分页查询")
    @GetMapping("/page")
    public R getSwStHandworkCleanRecordPage(Page page, SwStHandworkCleanRecord swStHandworkCleanRecord,String[] dates) {
        QueryWrapper<SwStHandworkCleanRecord> queryWrapper = Wrappers.query(swStHandworkCleanRecord);
        SwStHandworkCleanRecord swStHandworkCleanRecordObj = ObjectUtils.getDefaultObj(SwStHandworkCleanRecord.class);
        swStHandworkCleanRecord.setLineCode(swStHandworkCleanRecordObj.getLineCode());
        swStHandworkCleanRecord.setStationCode(swStHandworkCleanRecordObj.getStationCode());
        String startDate = null;
        String endDate = null;
        boolean dateFlag = false;
        if (dates != null) {
            dateFlag = true;
            String s = dates[0];
            try {
                String decode = URLDecoder.decode(s, "utf-8");
                String[] split = decode.split("&");
                startDate = split[0].substring(6);
                endDate = split[1].substring(6);
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
        }
        String dateCondition = swStHandworkCleanRecord.getCleanTimeDto();
        if (StringUtils.isNotBlank(dateCondition)) {
            queryWrapper.lambda().likeRight(SwStHandworkCleanRecord::getCleanTime, dateCondition);
        }
        return R.ok(swStHandworkCleanRecordService.page(page, queryWrapper
        .lambda()
        .between(dateFlag,SwStHandworkCleanRecord::getCleanTime,startDate,endDate).orderByDesc(SwStHandworkCleanRecord::getCleanTime)));
    }

    @RequestMapping("/getHandworkCleanRecord")
    public R getHandworkCleanRecord(@RequestParam Map<String,String> param){
        List<Map<String, Object>> swStHandworkCleanRecord = swStHandworkCleanRecordMapper.getHandworkCleanRecord(param);
        return R.ok(swStHandworkCleanRecord);
    }



    /**
     * 通过id查询手工清出数据 主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询", notes = "通过id查询")
    @GetMapping("/{id}")
    public R getById(@PathVariable("id") Integer id) {
        return R.ok(swStHandworkCleanRecordService.getById(id));
    }

    /**
     * 新增手工清出数据 主表
     *
     * @param swStHandworkCleanRecordDTO 手工清出数据 主表
     * @return R
     */
    @ApiOperation(value = "新增手工清出数据 主表", notes = "新增手工清出数据 主表")
    @SysLog("新增手工清出数据 主表")
    @PostMapping
    @PreAuthorize("@pms.hasPermission('swsthandworkcleanrecord_add')")
    public R save(@RequestBody SwStHandworkCleanRecordDTO swStHandworkCleanRecordDTO) {
        return R.ok(swStHandworkCleanRecordService.saveSwStHandworkCleanRecord(swStHandworkCleanRecordDTO));
    }

    /**
     * 修改手工清出数据 主表
     *
     * @param swStHandworkCleanRecordDTO 手工清出数据 主表
     * @return R
     */
    @ApiOperation(value = "修改手工清出数据 主表", notes = "修改手工清出数据 主表")
    @SysLog("修改手工清出数据 主表")
    @PutMapping
    @PreAuthorize("@pms.hasPermission('swsthandworkcleanrecord_edit')")
    public R updateById(@RequestBody SwStHandworkCleanRecordDTO swStHandworkCleanRecordDTO) {
        SwStHandworkCleanRecord handworkCleanRecord = swStHandworkCleanRecordService.getById(swStHandworkCleanRecordDTO.getSwStHandworkCleanRecord().getId());
        if(ObjectUtil.isNotEmpty(handworkCleanRecord)){
            String approvalStatus = handworkCleanRecord.getApprovalStatus();
            if("1".equals(approvalStatus)){
                return R.failed(StmConstans.failedEdit);
            }
        }
        return R.ok(swStHandworkCleanRecordService.updateSwStHandworkCleanRecord(swStHandworkCleanRecordDTO));
    }

    /**
     * 通过id查询手工清出数据（主表）历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过id查询手工清出数据（主表）历史记录", notes = "通过id查询手工清出数据（主表）历史记录")
    @GetMapping("getLogById/{id}")
    public R getLogById(@PathVariable("id") Integer id) {
        List<SwStmStationDataEntryLogDvo> LogInfoList = new ArrayList<>();
        List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                        .eq(SwStmStationDataEntryLog::getRelationId, id)
                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_HANDWORK_CLEAN_RECORD));
        //返回json串
        if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
            swStmStationDataEntryLogs.stream().forEach(x -> {
                JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                SwStmStationDataEntryLogDvo swStmStationDataEntryLogDvo = new SwStmStationDataEntryLogDvo();
                BeanUtils.copyProperties(x,swStmStationDataEntryLogDvo);
                swStmStationDataEntryLogDvo.setLogInfo(jsonObject);
                LogInfoList.add(swStmStationDataEntryLogDvo);
            });
        }
        //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
        return R.ok(LogInfoList);
    }

    /**
     * 通过记录表id查询具体的手工清出数据详情历史记录
     *
     * @param  id
     * @return R
     */
    @ApiOperation(value = "通过记录表id查询具体的手工清出数据详情历史记录", notes = "通过记录表id查询具体的手工清出数据详情历史记录")
    @GetMapping("getLogChildById/{id}")
    public R getLogChildById(@PathVariable("id") Integer id) {
        List<Object> LogInfoList = new ArrayList<>();
//        SwStmStationDataEntryLog swStmStationDataEntryLog = swStmStationDataEntryLogService.getBaseMapper()
//                .selectOne(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
//                        .eq(SwStmStationDataEntryLog::getMainId, id)
//                        .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_HANDWORK_CLEAN_RECORD));
            List<SwStmStationDataEntryLog> swStmStationDataEntryLogs = swStmStationDataEntryLogService.getBaseMapper()
                    .selectList(Wrappers.<SwStmStationDataEntryLog>lambdaQuery()
                            //.eq(SwStmStationDataEntryLog::getRelationId, id)
                            .eq(SwStmStationDataEntryLog::getMainId,id)
                            .eq(SwStmStationDataEntryLog::getLogTableName, StmTableCommon.SW_ST_HANDWORK_CLEAN_RECORD_DETAILS));
            //返回json串
            if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
                //List<String> LogInfoList = swStmStationDataEntryLogs.stream().map(SwStmStationDataEntryLog::getLogInfo).collect(Collectors.toList());
                if(CollectionUtil.isNotEmpty(swStmStationDataEntryLogs)){
                    swStmStationDataEntryLogs.stream().forEach(x -> {
                        JSONObject jsonObject = JSONObject.parseObject(x.getLogInfo());
                        LogInfoList.add(jsonObject);
                    });
                }
                return R.ok(LogInfoList);
            }
        return R.ok();
    }

    /**
     * 通过id删除手工清出数据 主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id删除手工清出数据 主表", notes = "通过id删除手工清出数据 主表")
    @SysLog("通过id删除手工清出数据 主表")
    @DeleteMapping("/{id}")
    @PreAuthorize("@pms.hasPermission('swsthandworkcleanrecord_del')")
    public R removeById(@PathVariable Integer id) {
        return R.ok(swStHandworkCleanRecordService.deleteCascadeById(id));
    }

    /**
     * 通过id删除手工清出数据 主表
     *
     * @param id id
     * @return R
     */
    @ApiOperation(value = "通过id查询手工录入详情", notes = "通过id查询手工录入详情")
    @GetMapping("/details/{id}")
    public R queryDetailsByid(@PathVariable Integer id) {
        return R.ok(swStHandworkCleanRecordService.queryDetailsByid(id));
    }

    /**
     * 批量删除子表
     * @param idList
     * @return
     */
    @SysLog("通过id批量删除手工清出数据")
    @DeleteMapping("/batchCascadeDel")
    @PreAuthorize("@pms.hasPermission('swsthandworkcleanrecord_batch_del')")
    @Transactional
    @ApiOperation(value = "通过id批量删除手工清出数据", notes = "通过id批量删除手工清出数据")
    public R batchRemoveById(@RequestBody List<Integer> idList) {
        List<SwStHandworkCleanRecord> list = swStHandworkCleanRecordService.list(new QueryWrapper<SwStHandworkCleanRecord>().lambda().in(SwStHandworkCleanRecord::getId, idList));
        List<Integer> deleteIds = list.stream().filter(x -> !x.getApprovalStatus().equals(CommonConstants.SUBMIT)).map(x -> x.getId()).collect(Collectors.toList());
        if(CollectionUtil.isEmpty(deleteIds)){
            return R.failed(StmConstans.failedDelete);
        }
        deleteIds.forEach(swStHandworkCleanRecordService::deleteCascadeById);
        return R.ok();
    }


    @ApiOperation(value = "导出钱箱未卸载数据", notes = "导出钱箱未卸载数据")
    @GetMapping("/export")
    public void export(Page page, SwStHandworkCleanRecord swStHandworkCleanRecord, HttpServletResponse response) {
        List<SwStHandworkCleanRecord> records = swStHandworkCleanRecordService.page(page, Wrappers.query(swStHandworkCleanRecord)).getRecords();
        try {
            R<List<SysDictItem>> inputDataStatus = systemUserService.getDictByType(StmConstans.STM_INPUT_DATA_STATUS);
            List<SysDictItem> dictData = inputDataStatus.getData();
            if (CollectionUtil.isNotEmpty(records)) {
                Map<String, String> map = dictData.stream().collect(Collectors.toMap(SysDictItem::getValue, SysDictItem::getLabel));
                for (SwStHandworkCleanRecord record : records) {
                    record.setApprovalStatus(map.get(record.getApprovalStatus()));
                }
            }
            response.setContentType("application/vnd.ms-excel");
            response.setCharacterEncoding("utf-8");
            String fileName = URLEncoder.encode("手工清出数据", "UTF-8");
            response.setHeader("Content-disposition", "attachment;filename=" + fileName + System.currentTimeMillis() + ".xlsx");
            EasyExcel.write(response.getOutputStream(), SwStHandworkCleanRecord.class).
                    sheet("手工清出数据").doWrite(records);
        } catch (IOException e) {
            log.error("手工清出数据失败");
        }
    }

}
